'''
Author: @zhyy
Date: 2021-01-27 14:23:31
LastEditors: @zhyy
LastEditTime: 2021-02-01 11:39:53
'''
#导入flask 项目需要的库
import os,time,logging
from logging.handlers import RotatingFileHandler
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_marshmallow import Marshmallow
from flask_cors import CORS
from config  import config
from celery import Celery
from celeryconfig import result_backend,broker
import celeryconfig

#日志配置
# log_path是存放日志的路径
cur_path = os.path.dirname(os.path.realpath(__file__))
log_path = os.path.join(os.path.dirname(cur_path), 'logs')
# 如果不存在这个logs文件夹，就自动创建一个
if not os.path.exists(log_path): os.mkdir(log_path)
logname = os.path.join(log_path, '%s.log'%time.strftime('%Y_%m_%d'))
# 默认日志等级的设置
logging.basicConfig(level=logging.INFO)
# 创建日志记录器，指明日志保存路径,每个日志的大小，保存日志的上限
file_log_handler = RotatingFileHandler(logname, maxBytes=1024 * 1024, backupCount=10)
# 设置日志的格式                   发生时间    日志等级     日志信息文件名      函数名          行数        日志信息
formatter = logging.Formatter('%(asctime)s--%(levelname)s--%(filename)s[lines:%(lineno)s]--function:%(funcName)s--msg:%(message)s')
# 将日志记录器指定日志的格式
file_log_handler.setFormatter(formatter)


# 实例化数据库
db = SQLAlchemy()
ma = Marshmallow()


celery = Celery(__name__, backend=result_backend,broker=broker)

# 工厂函数创建flask实例化对象
def create_app(even):
    #实例化flask对象
    app=Flask(__name__)

    #实例化配置文件
    app.config.from_object(config["default"])
    config["default"].init_app(app)
    
    #配置cors跨域请求伪造请求信息
    CORS(app, supports_credentials=True)

    #日志配置
    app.logger.addHandler(file_log_handler)

    #实例化数据库
    db.init_app(app)
    
    ma.init_app(app)

    # 实例化celery
    # register_celery(app)
    make_celery(app, backend=result_backend,broker=broker)

    #把注册到app对象上   
    register_blueprints(app)


    return app


# 注册蓝图
def register_blueprints(app):
    '''
    description:注册蓝图api,再通过api蓝图注册子蓝图模块 
    param app
    return {*}
    '''
    # api
    from app.api import create_blueprint_api
    app.register_blueprint(create_blueprint_api(), url_prefix='/api')
    # v2
    # from app.api.v2 import create_blueprint_v2
    # app.register_blueprint(create_blueprint_v2(),url_prefix='/api/v2')

def make_celery(app,backend, broker):
    celery = Celery(
        app.import_name,
        backend=backend,
        broker= broker
    )
    celery.config_from_object('celeryconfig')

    class ContextTask(celery.Task):
        def __call__(self, *args, **kwargs):
            with app.app_context():
                return self.run(*args, **kwargs)

    celery.Task = ContextTask
    return celery
    